package com.sf.dlb.service;

import com.sf.dlb.bean.BzyTastBean;
import com.sf.dlb.bean.BzyTastGroupBean;
import com.sf.dlb.bean.RequestBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.BzyExportRecodInfo;
import com.sf.dlb.jpa.model.BzyOauthInfo;
import com.sf.dlb.jpa.model.NewGetRecodInfo;
import com.sf.dlb.jpa.repository.BzyExportRecodRepository;
import com.sf.dlb.jpa.repository.NewGetRecodRepository;
import com.sf.dlb.utils.Global;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.HttpClientUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.TastGroupVO;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class BzyExportRecodService {
    private static Logger logger = LoggerFactory.getLogger(BzyExportRecodService.class);
    @Autowired
    private BzyExportRecodRepository bzyExportRecodRepository;
    @Autowired
    private NewGetRecodRepository newGetRecodRepository;
    @Autowired
    private BzyOauthService bzyOauthService;
    @Resource
    private Global global;

    /**
     * 手动获取八爪鱼的任务和任务组
     * @param requestBean
     * @return
     */
    public ResultVO getTask(RequestBean requestBean){
        //1 八爪鱼API授权；
        ResultVO resultVO=bzyOauthService.getOauth();
        if(resultVO.getCode()!=200){
            logger.info("getNewList getOauth is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getNewList getOauth is null");
        }
        BzyOauthInfo bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
        //获取任务组
        String taskgroupUrl=global.bzy_url+global.bzy_url_taskgroup;
        Map tastGroupMap=new HashMap<>();
        tastGroupMap.put("Authorization","bearer "+bzyOauthInfo.getAccessToken());
        HttpResponse taskgroupResponse= HttpClientUtils.getFromAndHeader(taskgroupUrl,tastGroupMap);
        List<BzyTastGroupBean.DataBean> dataBeans=hanlderTaskGroup(taskgroupResponse);
        if(CollectionUtils.isEmpty(dataBeans)){
            logger.info(" getTask BzyTastGroupBean is null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getTask BzyTastGroupBean is null");
        }
        ArrayList<TastGroupVO> tastGroupVO=new ArrayList<TastGroupVO>();
        for (BzyTastGroupBean.DataBean dataBean:dataBeans) {
            //封装VO
            TastGroupVO tastGroupVO1=new TastGroupVO();
            tastGroupVO1.setTaskGroupId(dataBean.getTaskGroupId());
            tastGroupVO1.setTaskGroupName(dataBean.getTaskGroupName());
            ArrayList<TastGroupVO.TasksBean> tastVOS=new ArrayList<>();
            tastGroupVO1.setTasks(tastVOS);
            //根据任务组，获取任务
            int taskGroupId=dataBean.getTaskGroupId();
            String taskUrl=global.bzy_url+global.bzy_url_task+"?taskGroupId="+taskGroupId;
            Map taskMap=new HashMap<>();
            taskMap.put("Authorization","bearer "+bzyOauthInfo.getAccessToken());
            HttpResponse taskResponse=HttpClientUtils.getFromAndHeader(taskUrl,taskMap);
            List<BzyTastBean.DataBean> dataBeans1=hanlderTask(taskResponse,taskGroupId);
            if(CollectionUtils.isEmpty(dataBeans1)){
                continue;
            }
            for (BzyTastBean.DataBean dataBean1:dataBeans1) {
                TastGroupVO.TasksBean tasksBean=new TastGroupVO.TasksBean();
                tasksBean.setTaskId(dataBean1.getTaskId());
                tasksBean.setTaskName(dataBean1.getTaskName());
                tastVOS.add(tasksBean);
            }
            tastGroupVO.add(tastGroupVO1);
        }
        return ResultVOUtil.success(tastGroupVO);
    }

    /**
     * 处理任务组请求
     * @param taskgroupResponse
     * @return
     */
    public List<BzyTastGroupBean.DataBean> hanlderTaskGroup(HttpResponse taskgroupResponse){
        int statusCode=taskgroupResponse.getStatusLine().getStatusCode();
        if(statusCode==401){
            logger.info("hanlderTaskGroup 401");
            ResultVO resultVO=bzyOauthService.getOauth(true);
            if(resultVO.getCode()!=200){
                logger.info("hanlderTaskGroup getOauth != 200");
                return null;
            }
            BzyOauthInfo bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
            String taskgroupUrl=global.bzy_url+global.bzy_url_taskgroup;
            Map tastGroupMap=new HashMap<>();
            tastGroupMap.put("Authorization","bearer "+bzyOauthInfo.getAccessToken());
            taskgroupResponse= HttpClientUtils.getFromAndHeader(taskgroupUrl,tastGroupMap);
            statusCode=taskgroupResponse.getStatusLine().getStatusCode();
        }
        String body;
        logger.info("hanlderTaskGroup statusCode is == "+statusCode);
        if(statusCode==200){
            HttpEntity httpEntity=taskgroupResponse.getEntity();
            if(null!=httpEntity){
                try {
                    body=EntityUtils.toString(httpEntity,"UTF-8");
                    BzyTastGroupBean bzyTastGroupBean=(BzyTastGroupBean)GsonUtils.getInstance().fromJson(body,BzyTastGroupBean.class);
                    if(null==bzyTastGroupBean){
                        logger.info("hanlderTaskGroup bzyTastGroupBean is null ");
                    }
                    if(!bzyTastGroupBean.getError().equals("success")){
                        logger.info("hanlderTaskGroup bzyTastGroupBean is errer ");
                    }
                    logger.info("hanlderTaskGroup body is == "+body);
                    return bzyTastGroupBean.getData();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.info("hanlderTaskGroup is errer ");
                }

            }
        }
        return null;
    }
    /**
     * 处理任务请求
     * @param taskResponse
     * @return
     */
    public List<BzyTastBean.DataBean> hanlderTask(HttpResponse taskResponse,int taskGroupId){
        int code=taskResponse.getStatusLine().getStatusCode();
        if(code==401){
            logger.info("hanlderTask 401");
            ResultVO resultVO=bzyOauthService.getOauth(true);
            if(resultVO.getCode()!=200){
                logger.info("hanlderTask getOauth != 200");
                return null;
            }
            BzyOauthInfo bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
            String  taskUrl=global.bzy_url+global.bzy_url_task+"?taskGroupId="+taskGroupId;
            Map taskMap=new HashMap<>();
            taskMap.put("Authorization","bearer "+bzyOauthInfo.getAccessToken());
            taskResponse=HttpClientUtils.getFromAndHeader(taskUrl,taskMap);
            code=taskResponse.getStatusLine().getStatusCode();
        }
        String body;
        logger.info("hanlderTask statusCode is == "+code);
        if(code==200){
            HttpEntity httpEntity=taskResponse.getEntity();
            if(null!=httpEntity){
                try {
                    body=EntityUtils.toString(httpEntity,"UTF-8");
                    BzyTastBean bzyTastBean=(BzyTastBean)GsonUtils.getInstance().fromJson(body,BzyTastBean.class);
                    if(null==bzyTastBean){
                        logger.info("hanlderTask bzyTastBean is null ");
                    }
                    if(!bzyTastBean.getError().equals("success")){
                        logger.info("hanlderTask bzyTastBean is errer ");
                    }

                    logger.info("hanlderTask body is == "+body);
                    return bzyTastBean.getData();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.info("hanlderTask is errer ");
                }

            }
        }
        return null;
    }
    /**
     * 手动添加八爪鱼的任务和任务组
     * @param tastGroupVO
     * @return
     */
    public ResultVO addBzyTask(TastGroupVO tastGroupVO){
        int taskGroupId=tastGroupVO.getTaskGroupId();
        String taskGroupName=tastGroupVO.getTaskGroupName();
        List<TastGroupVO.TasksBean> tasks=tastGroupVO.getTasks();
        List<BzyExportRecodInfo> bzyExportRecodInfos=new ArrayList<>();
        for (TastGroupVO.TasksBean tasksBean:tasks) {
            String taskId=tasksBean.getTaskId();
            String taskName=tasksBean.getTaskName();
            BzyExportRecodInfo bzyExportRecodInfo=new BzyExportRecodInfo();
            bzyExportRecodInfo.setUsername("tancs12345");
            bzyExportRecodInfo.setTaskGroupId(taskGroupId+"");
            bzyExportRecodInfo.setTaskGroupName(taskGroupName);
            bzyExportRecodInfo.setTaskId(taskId);
            bzyExportRecodInfo.setTaskName(taskName);
            bzyExportRecodInfo.setOffset(0);
            bzyExportRecodInfo.setSize(50);
            bzyExportRecodInfo.setTotal(0);
            bzyExportRecodInfo.setRestTotal(0);
            bzyExportRecodInfo.setCreateDate(new Date());
            bzyExportRecodInfo.setUpdateDate(new Date());
            bzyExportRecodInfos.add(bzyExportRecodInfo);
        }
        bzyExportRecodRepository.save(bzyExportRecodInfos);
        return ResultVOUtil.success();
    }
    /**
     * 处理导出请求
     * @param bzyOauthInfo
     * @param bzyExportRecodInfo
     * @return
     */
    public HttpResponse hanlderExportData(BzyOauthInfo bzyOauthInfo,BzyExportRecodInfo bzyExportRecodInfo){
        logger.info("hanlderExportData start ");
        StringBuffer exportdataUrl=new StringBuffer();
        exportdataUrl.append(global.bzy_url).append(global.bzy_url_exportdata).append("?")
                .append("taskId=").append(bzyExportRecodInfo.getTaskId()).append("&")
                .append("offset=").append(bzyExportRecodInfo.getOffset()).append("&")
                .append("size=").append(bzyExportRecodInfo.getSize());
        Map exportdataMap=new HashMap<>();
        exportdataMap.put("Authorization","bearer "+bzyOauthInfo.getAccessToken());
        HttpResponse exportdataResponse=HttpClientUtils.getFromAndHeader(exportdataUrl.toString(),exportdataMap);
        return exportdataResponse;
    }
    /**
     * 保存每次抓取的记录
     */
    public void saveGetRecodrs(NewGetRecodInfo newGetRecodInfo){
        logger.info("saveGetRecodrs start ");
        newGetRecodInfo.setEndTime(new Date());
        newGetRecodInfo.setCreateDate(new Date());
        newGetRecodInfo.setUpdateDate(new Date());
        newGetRecodRepository.save(newGetRecodInfo);
    }
    /**
     * 更新下次导数据偏移量
     * @param bzyExportRecodInfo
     */
    public void updateExportDataOffset(BzyExportRecodInfo bzyExportRecodInfo, int offerset,int total,int restTotal){
        logger.info("updateExportDataOffset start offerset={},total={},restTotal={}",offerset,total,restTotal);
        bzyExportRecodInfo.setOffset(offerset);
        bzyExportRecodInfo.setTotal(total);
        bzyExportRecodInfo.setRestTotal(restTotal);
        bzyExportRecodInfo.setUpdateDate(new Date());
        bzyExportRecodRepository.save(bzyExportRecodInfo);
    }
    /**
     * 请求八爪鱼数据
     * @param bzyOauthInfo
     * @param bzyExportRecodInfo
     * @return
     */
    public String getExportData(BzyOauthInfo bzyOauthInfo, BzyExportRecodInfo bzyExportRecodInfo){
        logger.info("getExportData start ");
        HttpResponse exportdataResponse=hanlderExportData(bzyOauthInfo,bzyExportRecodInfo);
        if(null==exportdataResponse){
            logger.info(" getExportData exportdataResponse is null ");
            return null;
        }
        int statusCode=exportdataResponse.getStatusLine().getStatusCode();
        //401 token失效
        if(statusCode==401){
            logger.info("getExportData access_token失效 401  ");
            ResultVO resultVO=bzyOauthService.getOauth(true);
            if(resultVO.getCode()!=200){
                logger.info("getExportData getOauth != 200");
                return null;
            }
            bzyOauthInfo=(BzyOauthInfo)resultVO.getData();
            exportdataResponse=hanlderExportData(bzyOauthInfo,bzyExportRecodInfo);//重新导出token
            if(null==exportdataResponse){
                logger.info(" getExportData 401 exportdataResponse is null ");
                return null;
            }
            statusCode=exportdataResponse.getStatusLine().getStatusCode();
        }
        String body ;
        logger.info("getExportData statusCode is == "+statusCode);
        if(statusCode==200){
            HttpEntity entity = exportdataResponse.getEntity();
            if (entity != null) {
                try {
                    body = EntityUtils.toString(entity, "utf-8");
                    return body;
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("getExportData is errer ");
                }
            }
        }
        return null;
    }
}
